package com.ztom.top100;

/**
 * 反转链表
 * <p>
 * https://leetcode-cn.com/problems/reverse-linked-list/
 *
 * @author ZhangTao
 */
public class Code60ReverseList {

    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public ListNode reverseList(ListNode head) {
        if (head == null) {
            return null;
        }
        ListNode pre = null;
        ListNode node = head;
        while (node != null) {
            ListNode next = node.next;
            node.next = pre;
            pre = node;
            node = next;
        }

        return pre;
    }

    /**
     * 递归
     *
     * @param head
     * @return
     */
    public ListNode reverseList1(ListNode head) {
        if (head == null) {
            return null;
        }
        return process(null, head);
    }

    private ListNode process(ListNode pre, ListNode node) {
        if (node == null) {
            return pre;
        }
        ListNode next = node.next;
        node.next = pre;
        pre = node;
        node = next;
        return process(pre, node);
    }
}
